const pool = require('../config/database');
const bcrypt = require('bcryptjs');

// 管理员身份验证中间件
exports.isAdmin = async (req, res, next) => {
    try {
        const token = req.headers.authorization?.split(' ')[1];

        if (!token) {
            return res.status(401).json({
                success: false,
                message: '未提供管理员令牌'
            });
        }

        // 在实际应用中，应该验证JWT令牌
        // 这里简化处理，从token中提取管理员ID
        const adminId = token.split('.')[0]; // 简化示例

        if (!adminId) {
            return res.status(401).json({
                success: false,
                message: '无效的管理员令牌'
            });
        }

        // 查询管理员信息
        const [admins] = await pool.execute(
            'SELECT * FROM users WHERE id = ? AND role = ? AND account_status = ?',
            [adminId, 'admin', 'active']
        );

        if (admins.length === 0) {
            return res.status(403).json({
                success: false,
                message: '无权访问此资源'
            });
        }

        req.admin = admins[0];
        next();

    } catch (error) {
        console.error('管理员身份验证错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
};

// 权限检查中间件
exports.checkPermission = (requiredPermission) => {
    return async (req, res, next) => {
        try {
            const adminId = req.admin.id;

            // 检查管理员是否拥有超级管理员权限
            if (req.admin.permission_level >= 100) {
                return next();
            }

            // 查询管理员拥有的权限
            const [permissions] = await pool.execute(`
                SELECT p.name 
                FROM permissions p
                JOIN role_permissions rp ON p.id = rp.permission_id
                JOIN user_roles ur ON rp.role_id = ur.role_id
                WHERE ur.user_id = ? AND p.name = ?
            `, [adminId, requiredPermission]);

            if (permissions.length === 0) {
                return res.status(403).json({
                    success: false,
                    message: '权限不足，无法执行此操作'
                });
            }

            next();

        } catch (error) {
            console.error('权限检查错误:', error);
            res.status(500).json({
                success: false,
                message: '服务器错误'
            });
        }
    };
};

// 记录管理员操作日志（对齐表结构: operation_type/target_id/target_type/operation_details/ip_address/user_agent）
exports.logOperation = async (adminId, operationType, targetEntity, targetId, details, ipAddress, userAgent) => {
    try {
        await pool.execute(
            `INSERT INTO admin_operation_logs (admin_id, operation_type, target_id, target_type, operation_details, ip_address, user_agent)
             VALUES (?, ?, ?, ?, ?, ?, ?)`,
            [adminId || null, operationType, targetId || null, targetEntity || null, details || null, ipAddress || null, userAgent || null]
        );
    } catch (error) {
        console.error('记录操作日志失败:', error);
        // 记录失败不应影响主流程，只记录错误
    }
};

// 验证密码
exports.verifyPassword = async (password, passwordHash) => {
    try {
        // 在实际应用中，应该使用bcrypt.compare
        // 这里为了演示，简化处理
        return password === 'admin123' || bcrypt.compareSync(password, passwordHash);
    } catch (error) {
        console.error('密码验证错误:', error);
        return false;
    }
};